package com.peng.community.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class ServiceLogAspect {

    //在方法执行前，记录用户访问日志
    //日志格式： 用户[ip]，在[时间]，访问了[某业务方法];
    @Pointcut("execution(* com.peng.community.service.*.*(..))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void serviceLog(JoinPoint joinPoint) {
        String method = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;//当使用MQ调用service时，确实会出现请求为空的情况
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        log.info("用户[{}]在时间[{}]访问了方法：[{}]", ip, time, method);
    }
}
